package org.ofbiz.wvtools.email;

import java.util.Locale;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceAuthException;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.service.ServiceValidationException;

import javolution.util.FastMap;

public class EmailServices {

    private static String module = EmailServices.class.getName();
    public static final String resource = "WvtoolsUiLabels";

    /**
     * 单发邮件
     * 
     * @param dctx
     * @param context
     * @return
     */
    public static Map<String, Object> sendSingleEmail(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	Locale locale = (Locale) context.get("locale");
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Map<String, Object> emailHistoryMap = FastMap.newInstance();
	// 返回结果
	String isSend = "failure";
	// 收件人
	String mail_to = (String) context.get("mailTo");
	// 主题
	String personalName = (String) context.get("personalName");
	// 标题
	String mailSubject = (String) context.get("mailSubject");
	// 内容
	String mailBody = (String) context.get("mailBody");
	String umId = (String) context.get("umId");
	String umPayToPartyId = (String) context.get("umPayToPartyId");
	try {

	    String mail_head_name = "";
	    String mail_head_value = "";

	    String userLoginId = userLogin.getString("userLoginId");
	    String partyId = userLogin.getString("partyId");
	    if (UtilValidate.isEmpty(partyId)) {
		partyId = userLoginId;
	    }
	    // 发送前记录日志
	    emailHistoryMap.put("statusId", "up");
	    emailHistoryMap.put("userLoginId", userLoginId);
	    emailHistoryMap.put("partyId", partyId);
	    emailHistoryMap.put("sendDate", UtilDateTime.nowTimestamp());
	    emailHistoryMap.put("sendUserName", "");
	    emailHistoryMap.put("receiveUserName", mail_to);
	    emailHistoryMap.put("title", personalName);
	    emailHistoryMap.put("subTitle", mailSubject);
	    emailHistoryMap.put("content", mailBody);
	    emailHistoryMap.put("createByUserLoginId", userLoginId);
	    if (UtilValidate.isNotEmpty(umId))
		emailHistoryMap.put("umId", umId);
	    if (UtilValidate.isNotEmpty(umPayToPartyId))
		emailHistoryMap.put("umPayToPartyId", umPayToPartyId);
	    emailHistoryMap.put("userLogin", userLogin);
	    dispatcher.runAsync("addEmailHistory", emailHistoryMap);
	    EmailUtils sendmail = new EmailUtils();
	    String host = "smtp.partner.outlook.cn";
	    // 这个是使用到的邮箱
	    String username = "eim@kejicloud.cn";
	    // 邮箱密码
	    String password = "eim.2020";

	    // 邮箱服务器
	    if (UtilValidate.isEmpty(host)) {
		GenericValue hostGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "service_for_email"),
			true);
		host = hostGv.getString("enumCode");
	    }
	    // 这个是你的邮箱用户名
	    if (UtilValidate.isEmpty(username)) {
		GenericValue emailUserGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "user_for_email"),
			true);
		username = emailUserGv.getString("enumCode");
	    }
	    // 你的邮箱密码
	    if (UtilValidate.isEmpty(password)) {
		GenericValue emailPwdGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "pwd_for_email"),
			true);
		password = emailPwdGv.getString("enumCode");
	    }

	    isSend = sendmail.send(host, username, password, mail_head_name, mail_head_value, mail_to, "", mailSubject,
		    mailBody, personalName);
	    // 发送后记录日志
	    emailHistoryMap.put("statusId", "down");
	    emailHistoryMap.put("userLoginId", userLoginId);
	    emailHistoryMap.put("partyId", partyId);
	    emailHistoryMap.put("servicesStatusId", isSend);
	    emailHistoryMap.put("sendDate", UtilDateTime.nowTimestamp());
	    emailHistoryMap.put("sendUserName", "");
	    emailHistoryMap.put("receiveUserName", mail_to);
	    emailHistoryMap.put("title", personalName);
	    emailHistoryMap.put("subTitle", mailSubject);
	    emailHistoryMap.put("content", mailBody);
	    emailHistoryMap.put("createByUserLoginId", userLoginId);
	    if (UtilValidate.isNotEmpty(umId))
		emailHistoryMap.put("umId", umId);
	    if (UtilValidate.isNotEmpty(umPayToPartyId))
		emailHistoryMap.put("umPayToPartyId", umPayToPartyId);
	    emailHistoryMap.put("userLogin", userLogin);
	    dispatcher.runAsync("addEmailHistory", emailHistoryMap);
	} catch (ServiceAuthException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (ServiceValidationException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (GenericServiceException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (GenericEntityException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	}
	result.put("isSend", isSend);
	return result;
    }

    public static Map<String, Object> sendSingleEmailHtml(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	Locale locale = (Locale) context.get("locale");
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Map<String, Object> emailHistoryMap = FastMap.newInstance();
	// 返回结果
	String isSend = "failure";
	// 收件人
	String mail_to = (String) context.get("mailTo");
	// 主题
	String personalName = (String) context.get("personalName");
	// 标题
	String mailSubject = (String) context.get("mailSubject");
	// 内容
	String mailBody = (String) context.get("mailBody");
	//附件
	String uploadPath = (String) context.get("uploadPath");
	try {

	    String mail_head_name = "";
	    String mail_head_value = "";

	    String userLoginId = userLogin.getString("userLoginId");
	    String partyId = userLogin.getString("partyId");
	    if (UtilValidate.isEmpty(partyId)) {
		partyId = userLoginId;
	    }
	    // 发送前记录日志
	    emailHistoryMap.put("statusId", "up");
	    emailHistoryMap.put("userLoginId", userLoginId);
	    emailHistoryMap.put("partyId", partyId);
	    emailHistoryMap.put("sendDate", UtilDateTime.nowTimestamp());
	    emailHistoryMap.put("sendUserName", "");
	    emailHistoryMap.put("receiveUserName", mail_to);
	    emailHistoryMap.put("title", personalName);
	    emailHistoryMap.put("subTitle", mailSubject);
	    emailHistoryMap.put("content", mailBody);
	    emailHistoryMap.put("createByUserLoginId", userLoginId);
	    emailHistoryMap.put("userLogin", userLogin);
	    dispatcher.runAsync("addEmailHistory", emailHistoryMap);
	    EmailUtils sendmail = new EmailUtils();

	    String host = "smtp.partner.outlook.cn";
	    // 这个是使用到的邮箱
	    String username = "eim@kejicloud.cn";
	    // 邮箱密码
	    String password = "eim.2020";

	    // 邮箱服务器
	    if (UtilValidate.isEmpty(host)) {
		GenericValue hostGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "service_for_email"),
			true);
		host = hostGv.getString("enumCode");
	    }
	    // 这个是你的邮箱用户名
	    if (UtilValidate.isEmpty(username)) {
		GenericValue emailUserGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "user_for_email"),
			true);
		username = emailUserGv.getString("enumCode");
	    }
	    // 你的邮箱密码
	    if (UtilValidate.isEmpty(password)) {
		GenericValue emailPwdGv = delegator.findOne("Enumeration", UtilMisc.toMap("enumId", "pwd_for_email"),
			true);
		password = emailPwdGv.getString("enumCode");
	    }

	    isSend = sendmail.sendHtml(host, username, password, mail_head_name, mail_head_value, mail_to, "",
		    mailSubject, mailBody, personalName,uploadPath);
	    // 发送后记录日志
	    emailHistoryMap.put("statusId", "down");
	    emailHistoryMap.put("userLoginId", userLoginId);
	    emailHistoryMap.put("partyId", partyId);
	    emailHistoryMap.put("servicesStatusId", isSend);
	    emailHistoryMap.put("sendDate", UtilDateTime.nowTimestamp());
	    emailHistoryMap.put("sendUserName", "");
	    emailHistoryMap.put("receiveUserName", mail_to);
	    emailHistoryMap.put("title", personalName);
	    emailHistoryMap.put("subTitle", mailSubject);
	    emailHistoryMap.put("content", mailBody);
	    emailHistoryMap.put("createByUserLoginId", userLoginId);
	    emailHistoryMap.put("userLogin", userLogin);
	    dispatcher.runAsync("addEmailHistory", emailHistoryMap);
	} catch (ServiceAuthException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (ServiceValidationException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (GenericServiceException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));
	} catch (GenericEntityException e) {
	    Debug.logError(e, e.getMessage(), module);
	    return ServiceUtil.returnError(
		    UtilProperties.getMessage(resource, "SendEmail.error", new Object[] { e.getMessage() }, locale));

	}
	result.put("isSend", isSend);
	return result;
    }

    /**
     * 记录邮件发送日志
     * 
     * @throws GenericEntityException
     */
    public static Map<String, Object> addEmailHistory(DispatchContext dctx, Map<String, ? extends Object> context)
	    throws GenericEntityException {
	Delegator delegator = dctx.getDelegator();
	Map<String, Object> result = ServiceUtil.returnSuccess();
	GenericValue emailHistory = delegator.makeValue("EmailHistory");
	String baseId = delegator.getNextSeqId("EmailHistory");
	emailHistory.set("baseId", baseId);
	emailHistory.setNonPKFields(context);
	emailHistory.create();
	return result;
    }
}
